<template>
	<view class="yp">
		<!-- 导航栏 -->
		<u-navbar
			title-color="#fff"
			back-icon-color="#ffffff"
			is-back="true"
			:background="background"
			:back-text-style="{ color: '#fff' }"
			title="发布图文"
			back-icon-name="nav-back"
			back-text="返回"
		>
			<view class="navbar-right" slot="right">
				<!-- <view class="message-box right-item">
					<u-icon name="chat" size="38"></u-icon>
					<u-badge count="18" size="mini" :offset="[-15, -15]"></u-badge>
				</view> -->
				<view class="dot-box right-item" @click="onPublish">发布</view>
			</view>
		</u-navbar>

		<!-- 发布内容 -->
		<view class="push-txt wid1p padd20 relative">
			<textarea placeholder="记录这一刻,分享给他人" v-model="form.contents" maxlength="500"></textarea>
			<view v-if="form.contents.length > 1" class="cuIcon-close clearValue right-top mt20 mr20 fo-gray" @click="form.contents = ''"></view>
			<view class="maxlength right-bottom mr20">{{ form.contents.length }}/500</view>
		</view>
		
		
		<!-- 图片上传 -->
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					<image :src="imgList[index]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index"><text class="cuIcon-close"></text></view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length < 4"><text class="cuIcon-cameraadd"></text></view>
			</view>
		</view>
	</view>
</template>

<script>
import { API$AddArticle } from '../../common/API/community.js';
export default {
	name: 'PushImgText',
	data() {
		return {
			background: {
				background: '#87ceeb'
			},
			imgList: [], // 发布的图片数组 (临时)
			form: {
				contents: '', // 发布的文字内容
				imgList: [] // 发布的图片数组 (传给后端的)
			}
		};
	},
	methods: {
		ChooseImage() {
			uni.chooseImage({
				count: 9, //默认9
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], //从相册选择
				success: res => {
					if (this.imgList.length != 0) {
						this.imgList = this.imgList.concat(res.tempFilePaths);
					} else {
						this.imgList = res.tempFilePaths;
					}
				}
			});
		},
		ViewImage(e) {
			uni.previewImage({
				urls: this.imgList,
				current: e.currentTarget.dataset.url
			});
		},
		// 删除图片
		DelImg(e) {
			uni.showModal({
				title: '警告',
				content: '是否删除这张照片？',
				cancelText: '再看看',
				confirmText: '再见',
				success: res => {
					if (res.confirm) {
						this.imgList.splice(e.currentTarget.dataset.index, 1);
					}
				}
			});
		},
		// 发布文章
		onPublish() {
			// 文字 或 图片不能为空
			if(!this.form.contents && this.imgList.length===0){
				return this.$pub.Toast('文字或图片不能为空！')
			}
			
			
			this.PushArticle({
				_id: this.$pub.getStorageSync('UserInfo')._id,
				contents: this.form.contents,
				imgList: this.form.imgList,
				PushType: 'img/text'
			});
		},
		// 发布接口封装
		async PushArticle(json) {
			uni.showLoading({ mask: true, title: '发布中~' });
			await this.UploadImg(this.imgList); // 先上传图片
			if (this.imgList.length != this.form.imgList.length) {
				this.$pub.Toast('网络错误,请稍后再试~'); //上传的图片未全部成功~
				uni.hideLoading();
				return;
			}
			try {
				let { code, msg ,data} = await API$AddArticle(json);
				data['isLookAll'] = false
				if (code === 200) {
					this.clearForm();
					setTimeout(() => {
						// 本地静态添加数据到社区主页的数据列表
						uni.$emit('FreshArticleList', {
							CallType: 'addArticle',
							data
						});
						this.$pub.Toast(msg);
					}, 500);
					this.$pub.back();
				}
			} catch (e) {
			} finally {
				uni.hideLoading();
			}
		},
		// 上传图片
		async UploadImg(imgList) {
			// uni.showLoading({ mask: true, title: '图上传中:0%' });
			for (let i = 0; i < imgList.length; i++) {
				try {
					let result = await uniCloud.uploadFile({
						cloudPath: 'articleImg/' + this.$tool.create_token() + '.png',
						filePath: imgList[i],
						onUploadProgress: function(progressEvent) {
							var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
							// uni.showLoading({ mask: true, title: '图上传中'+percentCompleted + '%' });
						}
					});
					if (result.fileID) {
						let res = await uniCloud.getTempFileURL({ fileList: [result.fileID] });
						this.form.imgList.push(res.fileList[0]);
					}
				} catch (err) {
					console.log(err);
				} finally {
					// uni.hideLoading();
				}
			}
		},
		// 清空表单
		clearForm() {
			this.imgList = '';
			this.form = {
				contents: '',
				imgList: []
			};
		}
	}
};
</script>

<style scoped lang="less">
.u-demo {
	//height: 200vh;
	height: calc(100% - 44px);
	height: calc(100% - 44px - constant(safe-area-inset-top));
	height: calc(100% - 44px - env(safe-area-inset-top));
}

.wrap {
	padding: 24rpx;
}

.navbar-right {
	margin-right: 24rpx;
	display: flex;
}

.search-wrap {
	margin: 0 20rpx;
	flex: 1;
}

.right-item {
	margin: 0 12rpx;
	position: relative;
	color: #ffffff;
	display: flex;
}

.message-box {
}

.slot-wrap {
	display: flex;
	align-items: center;
	flex: 1;
}

.map-wrap {
	display: flex;
	align-items: center;
	padding: 4px 6px;
	background-color: rgba(240, 240, 240, 0.35);
	color: #fff;
	font-size: 22rpx;
	border-radius: 100rpx;
	margin-left: 30rpx;
}

.map-wrap-text {
	padding: 0 6rpx;
}
</style>
